from typing import Optional
from PySide6.QtCore import QObject, Signal, QTimer
from loguru import logger
from ui.workers import SlowProcessWorker
from ..models.global_index_model import GlobalIndexModel


class GlobalIndexController(QObject):
    
    hk_data_loaded = Signal(list)
    global_data_loaded = Signal(list)
    
    def __init__(self):
        super().__init__()
        self.model = GlobalIndexModel()
        self.worker = None
        self.refresh_timer = QTimer()
        self.refresh_timer.timeout.connect(self.load_data)
        
    def start_auto_refresh(self, interval_ms: int = 10000):
        self.refresh_timer.start(interval_ms)
        
    def stop_auto_refresh(self):
        if self.refresh_timer.isActive():
            self.refresh_timer.stop()
            
    def load_data(self, days_limit: int = 250, force_refresh: bool = False):
        """加载全球指数数据
        
        Args:
            days_limit: 数据天数限制
            force_refresh: 是否强制刷新（用于分钟数据）
        """
        if self.worker and self.worker.isRunning():
            logger.info("已有 worker 在运行，跳过本次操作")
            return
            
        try:
            if force_refresh:
                logger.info("强制刷新模式：每次都重新获取分钟级数据")
            else:
                logger.info("日线数据模式：使用缓存机制")
                
            slow_tasks = {
                lambda: self.model.get_hk_index_data(days_limit=days_limit, force_refresh=force_refresh): self._on_hk_data_loaded,
                lambda: self.model.get_global_index_data(days_limit=days_limit, force_refresh=force_refresh): self._on_global_data_loaded
            }
            
            self.worker = SlowProcessWorker(slow_tasks)
            self.worker.start()
            
        except Exception as e:
            logger.exception(f"启动全球指数数据加载时出错: {e}")
            
    def _on_hk_data_loaded(self, table_data):
        try:
            if table_data:
                self.hk_data_loaded.emit(table_data)
                logger.info(f"成功加载 {len(table_data)} 个港股指数数据")
            else:
                logger.warning("未获取到港股指数数据")
        except Exception as e:
            logger.exception(f"更新港股指数数据时出错: {e}")

    def _on_global_data_loaded(self, table_data):
        try:
            if table_data:
                self.global_data_loaded.emit(table_data)
                logger.info(f"成功加载 {len(table_data)} 个全球指数数据")
            else:
                logger.warning("未获取到全球指数数据")
        except Exception as e:
            logger.exception(f"更新全球指数数据时出错: {e}")
    
    def clear_cache(self):
        """清除数据缓存"""
        try:
            self.model.clear_cache()
            logger.info("已清除全球指数数据缓存")
        except Exception as e:
            logger.exception(f"清除缓存时出错: {e}")
    
    def cleanup(self):
        self.stop_auto_refresh()
        if self.worker and self.worker.isRunning():
            self.worker.shutdown()